package com.roc.web.action.merchangerecord;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.BlackListBean;
import com.roc.bean.ChangeAgentCountBean;
import com.roc.bean.ChangeCheckCountBean;
import com.roc.bean.MerchantsChangeRecordBean;
import com.roc.bean.ReviseMerinfoBean;
//import com.roc.bean.ReviseMerinfoBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgncyService;
import com.roc.service.merchangerecord.MerchantsChangeRecordService;
import com.roc.service.reviseMerinfo.ReviseMerinfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.windcontroll.BlackListsSearchCondition;

@Component
@Namespace("/ysbMerinCheck")
@SuppressWarnings("serial")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MerchantsChangeRecordAction extends PaginationBaseAction{
	
	private Logger logger = LogManager.getLogger(MerchantsChangeRecordAction.class);
	private MerchantsChangeRecordSearchCondition searchCondition;
	
	
	private InputStream excelFile;
    @Autowired
    private IPageService pageService;
    @Autowired
    private IExcelService excelService;
    @Autowired
	IPageService pagenitionService;
    
/**
 * 初始化页面
 * @return
 * @throws Exception
 */
    @Action(value = "init", results = { @Result(name = "success", location = "/pages/merchangerecord/MerchantsChangeRecord.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		/*if(op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode()) || op.getRoleType().equals(Role.CLEAR_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;*/
		return SUCCESS;
	}
   /**
    * 云商宝商户变更记录查询
    * @return
    * @throws Exception
    */
    @Action(value = "queryMerRecord", results = { @Result(name = "success", location = "/pages/merchangerecord/MerchantsChangeRecord.jsp")
    })	
	public String queryMerRecord()throws Exception{
    	
    	
		 Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			/*if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
			{*/
				logger.info("云商宝商户变更记录");
	    		try {
	    			if(searchCondition==null){
	    				searchCondition=(MerchantsChangeRecordSearchCondition)getSearchConditionFromSession();
	    				if(searchCondition==null){
	    					searchCondition=new MerchantsChangeRecordSearchCondition();
	    				}
	    			}
	    			searchCondition.setOpId(String.valueOf(op.getId()));//获取当前人员ID 
	    			
	    			int rows=pagenitionService.countSQL(searchCondition);
	    			if(rows>0){
	    				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	    			}
	    			List<MerchantsChangeRecordBean> mcrList = new ArrayList<MerchantsChangeRecordBean>();
	    			dealWith(mcrList,searchRsList);
	    			
	    			getRequest().setAttribute("mcrList", mcrList);
	    			this.setTotalPage(this.calcuTotalPage(rows));
	    			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
	    			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
	    			addActionMessage("当前条件下统计到【"+rows+"】条记录");
	    			//this.setSearchCondition(searchCondition);
	    		} catch (Exception e) {
	    			
	    			logger.error(e.getMessage(),e);
	    			addActionError(e.getMessage());
	    			return ERROR;
	    		}		
	    	   return SUCCESS;
			/*}
			addActionError("无权限访问!!!");
			return ERROR;	*/
		}
		 
	
	
	
	/**
	 * 云商宝商户变更记录--导出
	 * @return
	 */
	@Action(value = "exportMerchantsChangeRecord", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/merchangerecord/MerchantsChangeRecord.jsp") })
	public String exportMerchantsChangeRecord(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		logger.info("导出云商宝商户变更记录excel开始");
		
		if(searchCondition==null){
			searchCondition=(MerchantsChangeRecordSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerchantsChangeRecordSearchCondition();
			}
		}
		
		try {
			searchCondition.setOpId(String.valueOf(op.getId()));
			
			int rows = pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<MerchantsChangeRecordBean> mcrList=new ArrayList<MerchantsChangeRecordBean>();
			dealWith(mcrList,searchRsList);
			logger.info("rows:" + rows + "    searchRsList.size():"+ searchRsList.size());
			HSSFWorkbook work=excelService.exportMerchantsChangeRecordList(mcrList,searchCondition);

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出云商宝商户变更记录excel结束");
		} catch (Exception e) {
			logger.info("导出云商宝商户变更记录异常："+e);
		}
		return SUCCESS;
	}
	
	
/**将查询出来的数据放入list里
 * 
 * @param mcrList
 * @param searchRsList
 * @return
 * @throws ServiceException
 */

	private List<MerchantsChangeRecordBean> dealWith(List<MerchantsChangeRecordBean> mcrList,List<Object> searchRsList) throws ServiceException {
		int i=1;
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				MerchantsChangeRecordBean mcr=new MerchantsChangeRecordBean();
				mcr.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				mcr.setNameOld(Constance.Null2EmptyTrim(obj[1]));
				mcr.setPhoneNo(Constance.Null2EmptyTrim(obj[2]));
				mcr.setAccountNoOld(Constance.Null2EmptyTrim(obj[3]));
				mcr.setBankNameOld(Constance.Null2EmptyTrim(obj[4]));
				mcr.setBankIdOld(Constance.Null2EmptyTrim(obj[5]));
				mcr.setAccountNoNew(Constance.Null2EmptyTrim(obj[6]));
				mcr.setBankNameNew(Constance.Null2EmptyTrim(obj[7]));
				mcr.setBankIdNew(Constance.Null2EmptyTrim(obj[8]));
				mcr.setCreateat(Constance.Null2EmptyTrim(obj[9]));
				mcrList.add(mcr);
				 i++;
			}
		}
		return mcrList;
	}



	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_MERCHANTS_CHANGE_RECORD_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERCHANTS_CHANGE_RECORD_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}
	


	public MerchantsChangeRecordSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(MerchantsChangeRecordSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName="商户变更记录表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	
}
